package club.gskj.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String ssoServerUrl;

    /**
     * 不用登陆既可访问
     *
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    /**
     * 需登录访问
     *
     * @param model
     * @param session
     * @param token   在服务认证器登陆成功后，保存redis中。返回token。该token从redis中获取用户信息
     */
    @GetMapping("/boss")
    public String employes(Model model, HttpSession session,
                           @RequestParam(value = "token", required = false) String token) {

        /**
         * 如果 请求url携带了token信息，说明该用户已登录。
         * 去 server获取当前token真正对应的用户信息
         */

        if (!StringUtils.isEmpty(token)) {
            // spring 封装的Http请求工具类
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userinfo?token=" + token, String.class);
            String body = responseEntity.getBody();
            session.setAttribute("loginUser", body);
        }

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:" + ssoServerUrl + "?redirect_url=http://client2.com:8082/boss";
        }
        List<String> list = new ArrayList<>();

        list.add("李四");
        list.add("赵六");
        model.addAttribute("employees", list);
        return "list";
    }
}
